import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

@SuppressWarnings({"all"})
// 扫描指定目录,并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
public class Main {
    public static void main(String[] args) throws IOException {
        // 输入路径和要查找的关键词
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要扫描的路径");
        File rootDir = new File(sc.next());
        System.out.println("请输入要查询的关键词：");
        String toFind = new String();
        // 递归进行扫描目录
        scanDir(rootDir, toFind);
    }

    private static void scanDir(File rootDir, String toFind) throws IOException {
        File[] files = rootDir.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                scanDir(f, toFind);
            } else {
                checkFile(f, toFind);
            }
        }
    }

    private static void checkFile(File f, String toFind) throws IOException {
        // 先检查文件名
        if (f.getName().contains(toFind)) {
            System.out.println(f.getCanonicalPath() + "文件名包含" + toFind);
        }
        // 检查文件内容
        InputStream inputStream = new FileInputStream(f);
        StringBuilder stringBuilder = new StringBuilder();
        Scanner sc = new Scanner(inputStream);
        while (sc.hasNextLine()) {
            stringBuilder.append(sc.nextLine() + "\n");
        }
        if (stringBuilder.indexOf(toFind) > -1) {
            System.out.println(f.getCanonicalPath() + "文件内容包含" + toFind);
        }
    }
}
